﻿using Microsoft.Extensions.Logging;
using PMS.SANY.MonOrderServer.Siemens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PMS.SANY.MonOrderServer
{
    public partial class WorkStation
    {
        public SiemensHelper Siemens { private set; get; }

        /// <summary>
        /// 下发订单至PLC
        /// </summary>
        /// <param name="retry">重试次数</param>
        /// <returns></returns>
        private async Task<bool> IssuedToPlcAsync(int retry = 3)
        {
            //写订单号
            var idx = 0;
            var result = Siemens.Write(Ip, OrderAddress.Address, OrderAddress.Type,OrderAddress.Count, WipOrderNo);
            while (!result && idx < 3)
            {//写入失败，再重试3次
                result = Siemens.Write(Ip, OrderAddress.Address, OrderAddress.Type, OrderAddress.Count, WipOrderNo);
                await Task.Delay(1000 * 3);
                idx++;
            }
            if (!result)
            {
                return false; 
            }

            //写物料号
            idx = 0;
            result = Siemens.Write(Ip, MeterAddress.Address, MeterAddress.Type, MeterAddress.Count, ProductNo);
            while (!result && idx < 3)
            {//写入失败，再重试3次
                result = Siemens.Write(Ip, MeterAddress.Address, MeterAddress.Type, MeterAddress.Count, ProductNo);
                await Task.Delay(1000 * 3);
                idx++;
            }
            if (!result) return false;

            //写计划数量
            idx = 0;
            result = Siemens.Write(Ip, QuantityAddress.Address, QuantityAddress.Type, QuantityAddress.Count, Quantity);
            while (!result && idx < 3)
            {//写入失败，再重试3次
                result = Siemens.Write(Ip, MeterAddress.Address, MeterAddress.Type, QuantityAddress.Count, ProductNo);
                await Task.Delay(1000 * 3);
                idx++;
            }

            return result;
        }
    }
}
